package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Log4j2
@RestController
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;


    @PostMapping(value = "/payments")
    public CommonResult addPayment(@RequestBody Payment payment){
        int result = paymentService.addPayment(payment);
        log.info("************插入结果*************"+result);
        if (result>0){
            return new CommonResult(200,"插入成功"+serverPort,result);
        }else {
            return new CommonResult(444,"写入数据库失败"+serverPort,null);
        }
    }


    @GetMapping(value = "/payment/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("*********查询结果********"+payment);

        if (payment==null){
            return new CommonResult(444,"查询失败"+serverPort,null);
        }else {
            return new CommonResult(200,"查询成功"+serverPort,payment);
        }
    }

    @ResponseBody
    @GetMapping("/payment/feign/timeout")
    public String paymentTimeout(){

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return serverPort+8002;

    }

}
